import 'dart:async';
import 'dart:ui';

import 'package:e_reception_flutter/utils/screen_utils.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter/painting.dart';
import 'package:photo_preview/photo_preview_export.dart';
import 'package:vg_base/vg_string_util_lib.dart';

///带描述指示器的滑动配置
class CustomWithDescAndPageSlideDelegate extends DefaultExtendedSlideDelegate {
  final List<PhotoPreviewInfoVo> imgVideoList;

  StreamController<int> pageChangeStatusStream = StreamController.broadcast();

  CustomWithDescAndPageSlideDelegate(this.imgVideoList);

  @override
  initState() {}

  @override
  ValueChanged<int> get pageChangeStatus {
    return (int page) {
      if (page < 0 || page >= (imgVideoList?.length ?? 0)) {
        return;
      }
      pageChangeStatusStream?.add(page);
    };
  }

  @override
  void dispose() {
    pageChangeStatusStream?.close();
    super.dispose();
  }

  @override
  SlideEndHandler get slideEndHandler => (
        Offset offset, {
        ExtendedImageSlidePageState state,
        ScaleEndDetails details,
      }) {
        //如果放大
        if ((state?.imageGestureState?.gestureDetails?.totalScale ??
                PhotoPreviewConstant.DEFAULT_TOTAL_SCALE) >
            (state?.imageGestureState?.imageGestureConfig?.initialScale ??
                PhotoPreviewConstant.DEFAULT_INIT_SCALE)) {
          return false;
        }
        //向上滑回弹
        if (offset.dy <= 0) {
          return false;
        }
        return offset.dy > 20;
      };

  @override
  Widget bottomWidget(bool isSlideStatus) {
    if ((imgVideoList?.length ?? 0) < 1) {
      return Container();
    }
    return AnimatedOpacity(
      opacity: isSlideStatus ? 0 : 1,
      duration: Duration(milliseconds: 80),
      child: _toBottomDescAndPageStatusWidget(),
    );
  }

  Widget _toBottomDescAndPageStatusWidget() {
    return Container(
      color: Colors.black.withOpacity(0.4),
      padding: EdgeInsets.only(bottom: ScreenUtils.getBottomBarH(context)),
      child: StreamBuilder<Object>(
          initialData: 0,
          stream: pageChangeStatusStream?.stream,
          builder: (context, snapshot) {
            final currentPage = snapshot?.data ?? 0;
            return Column(
              mainAxisSize: MainAxisSize.min,
              children: <Widget>[
                _toDescWidget(currentPage),
                Container(
                  height: 30,
                  alignment: Alignment.center,
                  child: _toPageStatusWidget(currentPage),
                )
              ],
            );
          }),
    );
  }

  Widget _toDescWidget(int currentPage) {
    final PhotoPreviewInfoVo itemVo =
        currentPage < 0 || currentPage >= (imgVideoList?.length ?? 0)
            ? null
            : imgVideoList?.elementAt(currentPage);
    return StringUtils.isEmpty(itemVo?.extra)
        ? Container()
        : Container(
            constraints: BoxConstraints(
              maxHeight: 105,
              minHeight: 42,
            ),
            padding: const EdgeInsets.all(12),
            child: SingleChildScrollView(
              physics: BouncingScrollPhysics(),
              child: AnimatedSwitcher(
                duration: Duration(milliseconds: 100),
                child: Container(
                  alignment: Alignment.topLeft,
                  key: ValueKey(itemVo?.extra),
                  child: Text(
                    itemVo?.extra ?? "",
                    maxLines: 200,
                    overflow: TextOverflow.ellipsis,
                    style: TextStyle(
                        color: Colors.white, fontSize: 14, height: 1.33),
                  ),
                ),
              ),
            ),
          );
  }

  Widget _toPageStatusWidget(int currentPage) {
    return Container(
      height: 7,
      child: ListView.separated(
          itemCount: imgVideoList?.length ?? 0,
          shrinkWrap: true,
          physics: NeverScrollableScrollPhysics(),
          scrollDirection: Axis.horizontal,
          padding: const EdgeInsets.only(left: 0, right: 0, top: 0, bottom: 0),
          keyboardDismissBehavior: ScrollViewKeyboardDismissBehavior.onDrag,
          itemBuilder: (BuildContext context, int index) {
            if ((imgVideoList?.length ?? 0) <= 1) {
              return Container();
            }
            return AnimatedContainer(
              width: (currentPage ?? 0) == index ? 15 : 7,
              duration: Duration(milliseconds: 200),
              decoration: ShapeDecoration(
                  shape: StadiumBorder(),
                  color: (currentPage ?? 0) == index
                      ? Colors.white
                      : Colors.white.withOpacity(0.5)),
            );
          },
          separatorBuilder: (BuildContext context, int index) {
            return SizedBox(
              width: 9,
            );
          }),
    );
  }
}
